package com.xiaomaoguai.fcp.pre.kepler.oss.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.experimental.UtilityClass;

/**
 * 生成 STS 信息的工具类
 *
 * @author WeiHui
 * @date 2019/1/23
 */
@UtilityClass
public class OssStsUtils {

	private static final String REGION_CN_HANGZHOU = "cn-hangzhou";

	private static final String POLICY_TEMPLATE = "{\"Version\":\"1\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"oss:GetObject\",\"oss:PutObject\",\"oss:DeleteObject\",\"oss:ListParts\",\"oss:AbortMultipartUpload\",\"oss:ListObjects\"],\"Resource\":[\"acs:oss:*:*:%s/*\"]}]}";

	/**
	 * 生成访问策略,参考官方文档
	 *
	 * @param bucketName 可以访问的文件夹
	 * @return policy 信息
	 * @link https://help.aliyun.com/document_detail/28664.html?spm=a2c4g.11186623.2.12.9f685328GbGIBv
	 */
	private static String createPolicy(String bucketName) {
		return String.format(POLICY_TEMPLATE, bucketName);
	}

	/**
	 * @param accessKeyId
	 * @param secret
	 * @param bucketName
	 * @param roleArn
	 * @return ossInfo
	 */
	public static AssumeRoleResponse genOssInfo(String accessKeyId, String secret, String bucketName, String roleArn) {
		try {
			// 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
			IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, secret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			// 创建一个 AssumeRoleRequest 并设置请求参数
			final AssumeRoleRequest request = new AssumeRoleRequest();
			request.setMethod(MethodType.POST);
			request.setProtocol(ProtocolType.HTTPS);
			request.setRoleArn(roleArn);
			request.setRoleSessionName(bucketName);
			request.setPolicy(createPolicy(bucketName));
			request.setDurationSeconds((long) (60 * 60));
			// 发起请求，并得到response
			return client.getAcsResponse(request);
		} catch (ClientException e) {
			throw new RuntimeException(e.getMessage());
		}
	}

}
